import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(ElementUI, VueAxios, axios)

let baseUrl = 'http://localhost:8082'
Vue.prototype.$baseUrl = baseUrl

Vue.config.productionTip = false
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    let token = window.localStorage.getItem("token");
    // config.headers.token=''
    // 在发送请求之前做些什么
    config.headers['token'] = token;

    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});


// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    if (response.data.code === 50004) {
        router.push('login')
    }

    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});


// 路由守卫
router.beforeEach((to, from, next) => {
    let token = window.localStorage.getItem("token");
    let routerArr = []
    // 改成同步 或者跳转逻辑卸载then里面
    token && axios.get(baseUrl + '/menu/getTree').then(res => {
        let menus = res.data.data;
        menus.map(item => {
            item.children.map(menu => {
                let newRouter = {
                    path: menu.path,
                    name: menu.name,
                    component: () => import('./views/' + menu.component + '.vue')
                }
                // 存入数组
                routerArr.push(newRouter);
            })
        })
        router.options.routes[0].children = routerArr;
        router.addRoutes(router.options.routes)
    })
    // 路径不是login且token为空时
    if (to.path != "/login" && token == null) {
        next({path: 'login'})
    }

    // 放行
    next();

})


new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
